/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * 个人信息
 */
import React, {Component} from "react";
import {
    StyleSheet,
    TouchableOpacity,
    Dimensions,
    Image,
    View,
    ToastAndroid,
    ScrollView,
    Button,
    Text,
    TextInput,
    SafeAreaView,
    DeviceEventEmitter
} from "react-native";
import SyanImagePicker from "react-native-syan-image-picker";
import color from "../../../widget/color";
import PhotoView from "../../../widget/homework/PhotoViewForLocal";
import NetTool from "../../../api/NetTool";
import api from "../../../api/api";
import method from "../../../api/method";
// import Toast from "react-native-easy-toast";
import define from "../../../utils/define";
import DeviceStorage from "../../../utils/DeviceStorage";
import {fetchPostRequest, fetchGetRequest} from "../../../api/NetworkTool";
import Tips from "react-native-root-tips";

let token = ''
DeviceStorage.get(define.token).then((args) => {
    token = 'Bearer ' + args;
})
const {width} = Dimensions.get('window')
type Props = {
    navigation: any,
}

export default class SubmitHomeworkScene extends Component<Props> {

    constructor(props) {
        super(props);
        this.state = {
            photos: [],
            index: 0,
            homeworkItem: this.props.navigation.state.params.info,
            lession_id: this.props.navigation.state.params.lession_id,
            homework_desc: ''
        };
    }

    static navigationOptions = ({navigation}: any) => ({
        headerTintColor: 'black',
        title: '提交作业',
        headerStyle: {
            // backgroundColor:color.primary,
        },

        headerRight: (
            <Text style={styles.submit_top} onPress={navigation.state.params.uploadData}>
                点击上传
            </Text>
        ),
        headerLeft: <TouchableOpacity onPress={()=>{
            navigation.goBack()
        }}>
            <Image style={{marginLeft:12}} source={require('../../../../res/img/gobal_back.png')}/>
        </TouchableOpacity>
    });


    render() {
        return (
            <SafeAreaView style={styles.container}>

                <View
                    style={{backgroundColor:'#EEEEEE',borderRadius:8,marginLeft:12,marginTop:17,marginRight:12,padding:10}}>
                    <Text style={{fontSize:14,fontWeight:'bold',color:'#333333'}}>作业描述</Text>
                    <Text style={{fontSize:12,color:'#888888',marginTop:8}}>{this.state.homework_desc}</Text>
                </View>

                <ScrollView style={{flex: 1}} contentContainerStyle={styles.scroll}>
                    {this.state.photos.map((photo, index) => {
                        let source = {uri: photo.uri};
                        return (
                            <View key={index+""} style={{height: 220,width:(width - 60) / 2,margin:12}}>

                                <TouchableOpacity key={index+""} style={styles.image}
                                                  onPress={()=>this.pressAction(source)}>
                                    <Image
                                        key={index+""}
                                        style={styles.image}
                                        source={source}
                                        resizeMode={"cover"}
                                    />
                                </TouchableOpacity>
                                <View style={{marginLeft:(width - 60) / 2 - 30,marginTop:8,}}>
                                    <TouchableOpacity key={index+""} style={styles.delete}
                                                      onPress={()=>this.deletePic(index,this.state.photos)}>
                                        <Image
                                            style={styles.delete_img}
                                            source={require('../../../../res/img/homework/delete.png')}/>
                                    </TouchableOpacity>
                                </View>
                            </View>
                        )
                    })}
                </ScrollView>
                <TouchableOpacity onPress={()=>this.selectPic()}>
                    <View style={styles.button_bottom}>
                        <Text style={{color:'white',fontSize:15,fontWeight:'bold'}}>选择作业图片</Text>
                    </View>
                </TouchableOpacity>
                <PhotoView ref={(photoView)=>{
                    this.photoView = photoView;
                }}/>
            </SafeAreaView>
        )


    }

    componentDidMount() {

        console.log('--------------------------------------', this.state.lession_id)
        // componentDidMount里面设置setParams
        this.props.navigation.setParams({
            uploadData: this.uploadPictures
        });

        //请求作业描述
        fetchGetRequest(api.homeworkDesc, method.get, {lesson_id: this.state.lession_id})
            .then(res => {
                console.log('============>', res)
                console.log('============>', res.homework_desc)
                this.setState({
                    homework_desc: res.homework_desc
                })
            })
            .catch(err => {

            })
    }

    uploadPictures = async() => {

        if (this.state.photos.length == 0) {
            Tips.showWarn('请选择作业图片进行上传！', {mask: true})
            return
        }

        let {info} = this.props.navigation.state.params

        let dataList = await this.uploadImage()

        console.log('ressss', params, dataList)

        let params = {
            lesson_id: this.state.lession_id,
            course_id: info.course_id,
            student_file: JSON.stringify(dataList),
        }

        console.log('--------------upload------------------------', this.state.lession_id)
        fetchPostRequest(api.submitHomework, method.post, params)
            .then(res => {
                console.log('res', res)
                Tips.hide()
                Tips.showSuccess('上传成功', {mask: true})
                this.props.navigation.goBack()
                this.props.navigation.state.params.callback('回调参数');
            })
            .catch(err => {
                Tips.hide()
                Tips.showFail('上传失败', {mask: true})
            })


    }

    uploadImage = async() => {
        let dataList = []

        if (this.state.photos.length > 9) {
            Tips.showWarn('最多上传9张图片', {mask: true})
            return
        }

        Tips.showLoading('上传中...')
        for (let photo of this.state.photos) {
            let fileNames = photo.uri.split('/')
            let fileName = fileNames[fileNames.length - 1]
            let params = {
                path: photo.uri,
                fileName: fileName,

            }
            let json = await NetTool.UploadHomeworkImage(params)

            if (json.data.code == 200) {
                dataList.push(json.data.output)
            }
        }
        return dataList
    }


    /**
     * 删除某张照片
     * @param index
     * @param oldPhotos
     * @returns {Array}
     */
    deletePic(index, oldPhotos) {

        // 更新原生图片数组
        SyanImagePicker.removePhotoAtIndex(index);
        if (!Array.isArray(oldPhotos)) {
            return []
        }
        for (let i = 0; i < oldPhotos.length; i++) {
            let value = oldPhotos[i]
            if (oldPhotos[index] === value) {
                oldPhotos.splice(i, 1)
            }
        }
        this.setState({
            photos: oldPhotos
        })

    }

    pressAction(source) {
        this.photoView.pressAction(source);
    }


    /**
     * 选择图片
     */
    selectPic() {
        if (this.state.photos.length >= 9) {
            Tips.showWarn('最多只能上传9张照片！', {mask: true})
            return
        }

        SyanImagePicker.showImagePicker({imageCount: 9}, (err, photos) => {
            if (!err) {
                let totalphotos = [...this.state.photos, ...photos]
                this.setState({
                    photos: totalphotos
                })

            } else {
                Tips.showWarn('取消选择！', {mask: true})
            }
        })
    }

}

const styles = StyleSheet.create({

    container: {
        flex: 1,
        backgroundColor: '#F9F9F9'
    },
    button_bottom: {
        backgroundColor: color.primary,
        width: width,
        height: 50,
        alignItems: 'center',
        justifyContent: 'center'
    },
    submit_top: {
        color: 'black',
        marginRight: 15,
        alignItems: 'center',
        justifyContent: 'center',
        fontSize: 16
    },
    scroll: {
        padding: 5,
        flexWrap: 'wrap',
        flexDirection: 'row'
    },
    image: {
        width: (width - 60) / 2,
        height: 220,
        backgroundColor: '#F0F0F0',
        alignItems: 'center',
        position: 'absolute',
    },
    delete: {
        width: 22,
        height: 22,
        alignItems: 'center',
        position: 'relative',
        backgroundColor: 'rgba(0,0,0,0.8)',
        justifyContent: 'center',
        borderRadius: 11,
    },
    delete_img: {
        width: 11,
        height: 12,
        alignItems: 'center',
        position: 'relative',
    },

});


